package net.maku.events.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.maku.events.dao.UserPointsRecordsDao;
import net.maku.events.dao.UserUnlockSiteDao;
import net.maku.events.entity.UserUnlockSiteEntity;
import net.maku.events.enums.ActivityTypeEnum;
import net.maku.events.query.ActivityRankQuery;
import net.maku.events.query.WalkUserSnapshotQuery;
import net.maku.events.service.UserPointsRecordsService;
import net.maku.events.vo.*;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.common.utils.Result;
import net.maku.events.service.ActivityBriskWalkService;
import net.maku.events.query.ActivityBriskWalkQuery;
import net.maku.member.dao.MemberUserDao;
import net.maku.member.entity.MemberUserEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * 健步走活动
 *
 * @author 阿沐 babamu@126.com
 * @since 1.0.0 2025-03-22
 */
@RestController
@RequestMapping("events/activity_brisk_walk")
@Tag(name = "健步走活动")
@AllArgsConstructor
@Slf4j
public class ActivityBriskWalkController {
    private final ActivityBriskWalkService activityBriskWalkService;

    private final UserPointsRecordsService userPointsRecordsService;


    @Autowired
    private MemberUserDao memberUserDao;

    @Autowired
    private UserUnlockSiteDao userUnlockSiteDao;


    @Autowired
    private UserPointsRecordsDao userPointsRecordsDao;


    @GetMapping("page")
    @Operation(summary = "分页")
    public Result<PageResult<ActivityBriskWalkVO>> page(@ParameterObject @Valid ActivityBriskWalkQuery query) {
        PageResult<ActivityBriskWalkVO> page = activityBriskWalkService.page(query);

        return Result.ok(page);
    }

    @GetMapping("get/join/org/{id}")
    @Operation(summary = "获取可参与的组织数组")
    public Result<Map<String, Object>> getJoinOrgIdList(@PathVariable("id") Long id) {
        return Result.ok(activityBriskWalkService.getJoinOrgIdList(id));
    }

    @GetMapping("/join/{id}")
    @Operation(summary = "参与活动")
    @PreAuthorize("hasAuthority('events:activity_brisk_walk:page')")
    public Result<String> joinActivity(@PathVariable("id") Long id) {
        activityBriskWalkService.joinActivity(id);
        return Result.ok();
    }

    @PostMapping("/join/new/user")
    @Operation(summary = "游客用户参与活动")
    public Result<String> joinActivityByNewUser(@RequestBody NewUserJoinActivityVO joinActivityVO) {
        activityBriskWalkService.joinActivityByNewUser(joinActivityVO);
        return Result.ok();
    }

    @PostMapping("/get/run/count")
    @Operation(summary = "获取微信用户的步数")
    @PreAuthorize("hasAuthority('events:activity_brisk_walk:page')")
    public Result<Map<String, Object>> getRunCount(@RequestBody WeRunRequestVO request) {
        return Result.ok(activityBriskWalkService.getRunCount(request));
    }

    @GetMapping("/unlock/{id}/{siteId}")
    @Operation(summary = "解锁站点")
    public Result<String> unlockSite(@PathVariable("id") Long id, @PathVariable("siteId") Long siteId) {
        activityBriskWalkService.unlockSite(id, siteId);
        return Result.ok();
    }

    @GetMapping("{id}")
    @Operation(summary = "设置站点信息及其他")
    @PreAuthorize("hasAuthority('events:activity_brisk_walk:info')")
    public Result<ActivityBriskWalkVO> get(@PathVariable("id") Long id) throws InterruptedException {
        return Result.ok(activityBriskWalkService.getInfoById(id));
    }

    @GetMapping("division/{id}")
    @Operation(summary = "设置站点信息及其他")
    @PreAuthorize("hasAuthority('events:activity_brisk_walk:info')")
    public Result<ActivityBriskWalkVO> division(@PathVariable("id") Long id) throws InterruptedException {
        return Result.ok(activityBriskWalkService.division(id));
    }

    @GetMapping("setJoinUserAndStep/{id}")
    @Operation(summary = "设置参与人数与步数及计算公里数")
    @PreAuthorize("hasAuthority('events:activity_brisk_walk:info')")
    public Result<ActivityBriskWalkVO> setJoinUserAndStep(@PathVariable("id") Long id) throws InterruptedException {
        return Result.ok(activityBriskWalkService.setJoinUserAndStep(id));
    }

    @GetMapping("setActivityPoints/{id}")
    @Operation(summary = "设置累计积分")
    @PreAuthorize("hasAuthority('events:activity_brisk_walk:info')")
    public Result<ActivityBriskWalkVO> setActivityPoints(@PathVariable("id") Long id) throws InterruptedException {
        return Result.ok(activityBriskWalkService.setActivityPoints(id));
    }

    @GetMapping("/view/competition/map/{id}")
    @Operation(summary = "查看竞赛地图")
    public Result<List<ActivityBriskWalkSiteVO>> viewCompetitionMap(@PathVariable("id") Long id) {
        return Result.ok(activityBriskWalkService.viewCompetitionMap(id));
    }

    @PostMapping("/save/user/snapshot")
    @Operation(summary = "健步走添加随手拍")
    public Result<Double> saveUserSnapshot(@RequestBody BriskWalkSnapshotVO vo) {
        return Result.ok(activityBriskWalkService.saveUserSnapshot(vo));
    }

    @PostMapping("/answer")
    @Operation(summary = "健步走答题")
    public Result<Double> answer(@RequestBody BriskWalkAnswerQuestionVO vo) {
        return Result.ok(activityBriskWalkService.answer(vo));
    }

    @GetMapping("/everyday/question/{walkFeatureId}")
    @Operation(summary = "每日答题的时候获取题目")
    public Result<List<ActivityContestQuestionVO>> everydayQuestion(@PathVariable("walkFeatureId") Long walkFeatureId) {
        return Result.ok(activityBriskWalkService.everydayQuestion(walkFeatureId));
    }

    @PostMapping("/look/snapshot")
    @Operation(summary = "查询随手拍")
    public Result<PageResult<UserSnapshotVO>> lookSnapshot(@RequestBody WalkUserSnapshotQuery query) {
        PageResult<UserSnapshotVO> page = activityBriskWalkService.lookSnapshot(query);
        return Result.ok(page);
    }

    @PostMapping("/user/self/rank")
    @Operation(summary = "个人排行")
    public Result<RankMemberUserVO> userSelfRank(@RequestBody ActivityRankQuery query) {
        query.setActivityType(ActivityTypeEnum.WALK_ACTIVITY.getBusinessType());
        return Result.ok(userPointsRecordsService.userSelfRank(query));
    }

    @PostMapping("/user/rank")
    @Operation(summary = "个人排行榜、今日排行榜")
    public Result<List<RankMemberUserVO>> userRank(@RequestBody ActivityRankQuery query) {
        return Result.ok(userPointsRecordsService.getRank(query.getActivityId(), ActivityTypeEnum.WALK_ACTIVITY.getBusinessType(), query.getTodayFlag()));
    }

    @PostMapping("/user/rank/page")
    @Operation(summary = "个人排行榜、今日排行榜分页")
    public Result<PageResult<RankMemberUserVO>> userRankPage(@RequestBody ActivityRankQuery query) {
        query.setActivityType(ActivityTypeEnum.WALK_ACTIVITY.getBusinessType());
        PageResult<RankMemberUserVO> page = userPointsRecordsService.getRankPage(query);
        return Result.ok(page);
    }

    @GetMapping("/org/rank/{activityId}")
    @Operation(summary = "单位排行榜")
    public Result<List<RankOrgVO>> userRank(@PathVariable("activityId") Long activityId) {
        return Result.ok(userPointsRecordsService.getRankOrg(activityId, ActivityTypeEnum.WALK_ACTIVITY.getBusinessType()));
    }

    @GetMapping("/self/card/{briskWalkId}")
    @Operation(summary = "获取我的卡片")
    public Result<SelfCardVO> getSelfCard(@PathVariable("briskWalkId") Long briskWalkId) {
        return Result.ok(activityBriskWalkService.getSelfCard(briskWalkId));
    }

    @GetMapping("/get/already/answer/{walkFeatureId}")
    @Operation(summary = "查看每日答题")
    public Result<List<AlreadyAnswerQuestionBankVO>> alreadyAnswer(@PathVariable("walkFeatureId") Long walkFeatureId) {
        return Result.ok(activityBriskWalkService.alreadyAnswer(walkFeatureId));
    }

    //    @Autowired
//    RedisCache redisCache;
//
    @GetMapping("/redis/value")
    @Operation(summary = "获取redis的值")
    public Result<Void> getRedisValue() {
        activityBriskWalkService.autoLightLastStationTest();
        return Result.ok();
//        List<UserJourneyEntity> userJourneyEntityList = new ArrayList<>();
//        String key = "step_key:" + 18 + ":";
//        Pattern NUMERIC_PATTERN = Pattern.compile("^[-+]?\\d+(\\.\\d+)?([eE][-+]?\\d+)?$");
//        Map<Object, Object> result = redisCache.getValuesByPrefix(key);
//        Map<String, Set<Long>> stepDateMap = new HashMap();
//        result.forEach((itemKey, value) -> {
//            if (NUMERIC_PATTERN.matcher(value.toString()).matches()) {
//                String userId = String.valueOf(itemKey).split(":")[2];
//                String stepDate = String.valueOf(itemKey).split(":")[3];
//                Set<Long> userIdList = stepDateMap.get(stepDate);
//                if (CollectionUtils.isEmpty(userIdList)) {
//                    userIdList = new HashSet<>();
//                }
//                userIdList.add(Long.parseLong(userId));
//                stepDateMap.put(stepDate, userIdList);
//                String count = value.toString();
//                userIdList.add(Long.parseLong(userId));
//                UserJourneyEntity entity = new UserJourneyEntity();
//                entity.setUserId(Long.parseLong(userId));
//                entity.setStepDate(LocalDate.ofEpochDay(Long.parseLong(stepDate)));
//                entity.setWalkActivityId(18L);
//                entity.setStepNumber(Integer.parseInt(count));
//                userJourneyEntityList.add(entity);
//            }
//        });
//        System.out.println(userJourneyEntityList);
//        return Result.ok();
    }
    @GetMapping("/unlockFixedSite/{mobile}/{siteNumber}")
    public Result<Object> unlockFixedSite(@PathVariable String mobile,
                         @PathVariable String siteNumber){
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(siteNumber)){
            return Result.error("手机号或者地图数量未填");
        }
        return activityBriskWalkService.unlockFixedSite(mobile,siteNumber);
    }



}